package com.glodon.paas.framework.registry.server.zk.watcher;

import com.glodon.paas.framework.registry.server.zk.util.ZooKeeperServerUtils;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Watch the changes of all clients of one dedicate service
 *
 * @author Don Li
 */
public class ServiceWatcher implements Watcher {
    private final Logger LOGGER = LoggerFactory.getLogger(ServiceWatcher.class);

    private ZooKeeper zk;

    public ServiceWatcher(ZooKeeper zk) {
        this.zk = zk;
    }

    @Override
    synchronized public void process(WatchedEvent event) {
        if (event.getType() == Event.EventType.NodeChildrenChanged) {
            // todo renew the server side cache
            // todo watcher for each service
            try {
                /*Stat stat = new Stat();
                List<String> clients = zk.getChildren(event.getPath(), this);
                if (clients.size() == 0) {
                    // mark the service as unavailable
                    ServiceBasic basic = (ServiceBasic) SerializationUtils.deserialize(zk.getData(event.getPath(), false, stat));
                    if (basic.getStatus() == ServiceStatus.AVAILABLE) {
                        basic.setStatus(ServiceStatus.UNAVAILABLE);
                        zk.setData(event.getPath(), SerializationUtils.serialize(basic), stat.getVersion());
                    }
                } else {
                    for (String client : clients) {
                        String path = event.getPath() + "/" + client;
                        ClientBasic basic = (ClientBasic) SerializationUtils.deserialize(zk.getData(path, false, stat));

                    }
                }*/
                ZooKeeperServerUtils.updateServiceStatus(zk, event.getPath());
            } catch (Exception e) {
                LOGGER.error("Fail to set ServiceWatcher", e);
            }
        }
    }
}
